package ru.nsu.fit.iconveyor.conveyor.utils.file;

import java.io.File;

/**
 * This static class deletes directory and all files, which it contains.
 *
 * @author Timur Zolotuhin (tzolotuhin@gmail.com)
 */
public class DeleteDirectory {
    /**
     * Removes directory if fileName is directory and file if fileName is file.
     * @param fileName - path to file.
     * @return true if fileName is exist and it was deleted, false otherwise.
     */
	public static boolean delete(String fileName) {
		File directory = new File(fileName);

		// make sure directory exists
		if (!directory.exists()) {
			return false;
		} else {
			return delete(directory);
		}
	}

	private static boolean delete(File file) {

		if (file.isDirectory()) {

			// directory is empty, then delete it
			if (file.list().length == 0) {
				return file.delete();
			} else {
				// list all the directory contents
				String files[] = file.list();

				for (String temp : files) {
					// construct the file structure
					File fileDelete = new File(file, temp);

					// recursive delete
					delete(fileDelete);
				}

				// check the directory again, if empty then delete it
				if (file.list().length == 0) {
					return file.delete();
				}
			}

		} else {
			// if file, then delete it
			return file.delete();
		}
        return false;
	}
}
